<?php
/**
 * Template Name: login_success
 *
 * 通用的登录注册
 * date:2011/4/11 
 * @author Ryan 
 * 
 */


//get_header();

if (!isset($_SESSION)) {
 	session_start();
	//session_regenerate_id();
}

$username = $_POST['username'];
$password = $_POST['password'];
$login_type = $_POST['login_type'];

$login_success = false;
$user = false;

$url = $_POST['url_refrence'] == '' ? get_bloginfo('home') : $_POST['url_refrence'];

if($login_type == 'sina'){
	$sina_id = $_POST['out_id'];
	$display_name = $_POST['out_name'];
	if(!username_exists('[sina]'.$sina_id)){
		$user_activtion_key = wp_generate_password(24, false);
	
		global $wpdb;
		$wpdb->insert('wp_users', array('user_login'=>'[sina]'.$sina_id ,
							'display_name'=>$display_name, 
							'user_registered' => gmdate('Y-m-d H:i:s'), 
							'user_status' => 0));
		$useid = (int) $wpdb->insert_id;
		
		add_user_meta($useid, 'login_type', 'sina');
		add_user_meta($useid, 'ref_id', $sina_id);
		
		$user = get_userdata($useid);
	}else{
		$user = get_userdatabylogin('[sina]'.$sina_id);
	}
	
	$login_success = true;
}else{
	if ($username && $password){
		
		$user = get_userdatabylogin($username);
		if($user){
			if(user_pass_ok($username, $password)){
				$url = $_POST['url_refrence'] == '' ? get_bloginfo('home') : $_POST['url_refrence'];
				$login_success = true;
			}else 
				$login_success = false;
		}else
			$login_success = false;
	}
}

if ($login_success){
				
	$_SESSION['userdata'] = $user;
	
	$user_cookie = $_COOKIE['youxisoso_user'];
	$user_cookie = explode(":", $user_cookie);
	
	if ($user_cookie && count($user_cookie) == 2 && $user_cookie[1] != 1){ 
		//如果cookie已经存在,并且是一个游客的cookie
		deleteCustomLog($user_cookie[0], $user->id);
	}
		
	$user_cookie = array($user->id, '1');
	setcookie('youxisoso_user', join($user_cookie, ":"), time()+3600*24*30);
	
	?>
	<html>
	<head></head>
	<body>
	<script type="text/javascript">

		window.onload= function (){
			window.location = <?php echo '"'.$url.'";';?>
			};
	</script>
	
	<p>您已成功登录，现在转向登录前页面。</p>
	<!-- 
		<p>您已登录成功！页面将在5秒后转向登录前页面，您也可以手动点击以下链接。</p>
		<p><a href="<?php echo $url;?>" >登录前页面。</a></p>
		<p><a href="<?php echo get_bloginfo('home');?>" >游戏搜搜首页。</a></p>
	 -->
	</body>
	</html>
	<?php
}else {
	?>
	<div id="zc">
		<p>登录失败。</p>
	</div>
<?php } ?>